<?php

namespace App\Console\Commands;

use App\Enum\SmsScheduleEnum;
use App\Lib\sms\AliSms;
use App\Models\OrderModel;
use App\Models\ScheduleRecordModel;
use App\Models\SmsScheduleModel;
use App\Models\TravelAddressModel;
use Illuminate\Console\Command;

class saveOrderAddressCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:save-address {send_num?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '保存订单地址到用户常用地址';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $sendNum = $this->argument('send_num') ?? 10;

        while(1) {
            $sencond = date('s');

            if ($sencond >= 55) {
                $this->info("saveOrderAddressCommand sencond = $sencond, wait for next time.");
                break;
            }else  $this->info("saveOrderAddressCommand sencond = $sencond, keep going.");

            $record = ScheduleRecordModel::query()->where(['schedule'=>'save-order-address'])->first(['record_id','id']);
            if( empty($record) ) {
                $this->error('saveOrderAddressCommand: could not find the row of <b>save-order-address</b>');
                break;
            }
            $record = $record->toArray();
            $recordId = $record['record_id'];
            $scheduleId = $record['id'];

            $rows = OrderModel::query()->where('id', '>', $recordId)->orderBy('id', 'asc')->limit($sendNum)->get()->toArray();
            $startFields = ['address'=>'start_address_detail','location'=>'start_location','short_address'=>'start_address','adcode'=>'start_adcode'];
            $endFields = ['address'=>'end_address_detail','location'=>'end_location','short_address'=>'end_address','adcode'=>'end_adcode'];
            if (!empty($rows)) {
                $newRecordId = 0;
                foreach ($rows as $row) {
                    $data = [
                        'user_id' => $row['user_id'], 'platform_id' => $row['platform_id'],
                        'status' => 1, 'remark' => '从订单中取得。'
                    ];
                    // start address saving
                    $insert=true;
                    foreach($startFields as $dKey=>$skey){
                        if(empty( $row[$skey])){
                            $insert=false;
                            break;
                        }
                        $data[$dKey]    = $row[$skey];
                    }
                    $insert && $this->addAddressIfNotExists($data);
                    // end address saving
                    $insert=true;
                    foreach($endFields as $dKey=>$skey){
                        if(empty( $row[$skey])){
                            $insert=false;
                            break;
                        }
                        $data[$dKey]    = $row[$skey];
                    }
                    $insert && $this->addAddressIfNotExists($data);
                    $newRecordId = $row['id'];
                }
                if( $newRecordId != 0 )
                    ScheduleRecordModel::query()->where(['id'=>$scheduleId])->update(['record_id'=>$newRecordId]);
            }
            sleep(2);
        }
        //
        return 0;
    }
    //不存在则插入
    private function addAddressIfNotExists($data)
    {
        $location = explode(',', $data['location']);
        $data['location'] = $location[1].','.$location[0];
        $exists = TravelAddressModel::query()->where(['user_id'=>$data['user_id'],'location'=>$data['location']])->exists();
        if( !$exists ){
            TravelAddressModel::create($data);
        }
    }
}
